package io.gitee.cofenghen.jdbctempleplus.support.dialect;

import io.gitee.cofenghen.jdbctempleplus.model.PageResult;
import io.gitee.cofenghen.jdbctempleplus.model.SelectPageMapListSqlModel;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Map;

public class DefaultSQLDialect implements DialectStrategy {
    @Override
    public SelectPageMapListSqlModel getLimitSql(String sql_table, String sql_column, String sql_where, String pk_Filed, String orderField, String orderType, LinkedHashMap<String, String> defaultOrderFieldMap, int pageIndex, int pageSize, String sql_column_top, boolean selectCount) {
        SelectPageMapListSqlModel selectPageMapListSqlModel=new SelectPageMapListSqlModel();
        if (null==defaultOrderFieldMap)
            defaultOrderFieldMap=new LinkedHashMap<>();

        if (null==sql_where)
            sql_where="";


        PageResult<Map<String, Object>> result = new PageResult<>();
        //设置默认
        if (pageIndex == 0)
            pageIndex = 1;
        if (pageSize == 0)
            pageSize = 10; //默认10笔数据
        result.setTotalRecordCount(0L);


        String sql = "select  {0}   from  " + sql_table ;
        if (org.springframework.util.StringUtils.hasText(sql_where))
        {
            sql+=" where ";

            if (sql_where.trim().toLowerCase().startsWith("and"))
            {
                sql_where=  sql_where.trim().substring(3)+" ";
            }
        }


//读取数量

        if (selectCount) {
            var sql_count = MessageFormat.format(sql, " count(*) ") + sql_where;
            selectPageMapListSqlModel.setCountSql(sql_count);

        }

        boolean isContainFK_Orderbyid =false;
        StringBuilder orderWhereBuilder =new StringBuilder();

        if (StringUtils.hasText(orderField) &&StringUtils.hasText(orderType)&&
                (orderType.toLowerCase().equals("asc") || orderType.toLowerCase().equals("desc"))) {
            orderWhereBuilder.append(" "+ orderField+" "+orderType);

            if (orderField.toLowerCase().equals(pk_Filed.toLowerCase()))
                isContainFK_Orderbyid = true;
        }
        else
        {
            for (Map.Entry<String, String> entry : defaultOrderFieldMap.entrySet()) {
                if (!StringUtils.hasText(entry.getKey()) || !StringUtils.hasText(entry.getValue()))
                    continue;
                if (!(entry.getValue().toLowerCase().equals("asc") || entry.getValue().toLowerCase().equals("desc")))
                    continue;
                if (entry.getKey().toLowerCase().equals(pk_Filed.toLowerCase()))
                    isContainFK_Orderbyid = true;
                if(orderWhereBuilder.length()>0)
                    orderWhereBuilder.append(",");
                orderWhereBuilder.append(" "+ entry.getKey()+" "+entry.getValue());


            }
        }

        if (!isContainFK_Orderbyid)
        {
            if (orderWhereBuilder.length()>0)
                orderWhereBuilder.append(",");
            orderWhereBuilder.append(" "+ pk_Filed+" asc ");
        }
        //  sql_where+=" order by "+orderWhereBuilder.toString();

        if (!StringUtils.hasText(sql_column_top))
            sql_column_top="temp2.*";
        // var sql_page = "select "+sql_column_top+" from (select rownum as rn,temp1.* from(" + MessageFormat.format(sql, sql_column) + sql_where + "    )    temp1 where rownum <="+ (pageSize * pageIndex)+")  temp2   where temp2.rn>="+(pageSize * (pageIndex - 1) + 1) ;


        String sql_column_over= ", ROW_NUMBER() OVER (order by "+orderWhereBuilder.toString()+") AS rn ";


        var sql_page = "select "+sql_column_top+" from ( " + MessageFormat.format(sql, sql_column+sql_column_over) + sql_where + "    )    temp2   where  rn <="+ (pageSize * pageIndex)+"  and  rn>="+(pageSize * (pageIndex - 1) + 1) ;


        selectPageMapListSqlModel.setDetailSql(sql_page);
        return  selectPageMapListSqlModel;
    }
}
